function add(a, b) {
	// 0 + 0 = 5
	if (!Number(a) && !Number(b)) {
		return 5
	}
	return a + b < 10 ? a + b : ((a + b) % 10) + 1
}

function getPersonCode(brithday = '19950815') {
	const [E, F, G, H, C, D, A, B] = brithday.split('').map((el) => Number(el))
	const I = add(A, B)
	const J = add(C, D)
	const K = add(E, F)
	const L = add(G, H)
	const M = add(I, J)
	const N = add(K, L)
	const O = add(M, N)
	const P = add(M, O)
	const Q = add(N, O)
	const R = add(Q, P)
	const X = add(I, M)
	const W = add(J, M)
	const S = add(X, W)
	const U = add(L, N)
	const V = add(K, N)
	const T = add(V, U)
	return {
		A,
		B,
		C,
		D,
		E,
		F,
		G,
		H,
		I,
		J,
		K,
		L,
		M,
		N,
		O,
		P,
		Q,
		R,
		X,
		W,
		S,
		U,
		T,
		V,
	}
}

export function getPrimaryCode(brithday) {
	const personCode = getPersonCode(brithday)
	return personCode.O
}

export function getUnionCodes(brithday) {
	const personCode = getPersonCode(brithday)
	const codeNameArr = ['MNO', 'IJM', 'KLN', 'XWS', 'QPR', 'VUT']
	return codeNameArr.map((el) => {
		return el
			.split('')
			.map((el) => personCode[el])
			.join('')
	})
}

export function getWealthCode(brithday) {
	const personCode = getPersonCode(brithday)
	const {
		S,
		R,
		T
	} = personCode
	return [S, R, T].join('')
}

export function getStarCodeObj(brithday) {
	const personCode = getPersonCode(brithday)
	const {
		I,
		L,
		O
	} = personCode
	if (I === L && L === O) {
		return {
			isThreeStarCode: true,
			code: [I],
		}
	}
	return {
		isThreeStarCode: false,
		code: [...new Set([I, L])].filter((el) => el !== O),
	}
}

export function getPartnerCode(brithday, partnerBrithday) {
	const primaryCode = getPrimaryCode(brithday)
	const partnerPrimaryCode = getPrimaryCode(partnerBrithday)
	return add(primaryCode, partnerPrimaryCode)
}

export function getInternalCode(brithday) {
	const personCode = getPersonCode(brithday)
	const {
		M,
		N,
		I,
		J,
		K,
		L,
	} = personCode
	const {
		code
	} = getStarCodeObj(brithday)
	const primaryCode = getPrimaryCode(brithday)
	const notCodeArr = [...code, primaryCode].filter(el => ![1, 4].includes(el))
	return [M, N, I, J, K, L].filter(el => !notCodeArr.includes(el))
}

export function getExternalCode(brithday) {
	const personCode = getPersonCode(brithday)
	const {
		S,
		X,
		W,
		R,
		Q,
		P,
		V,
		U,
		T,
		O,
	} = personCode
	const {
		code
	} = getStarCodeObj(brithday)
	const primaryCode = getPrimaryCode(brithday)
	const notCodeArr = [...code, primaryCode].filter(el => ![1, 4].includes(el))
	return [S, X, W, R, Q, P, V, U, T].filter(el => !notCodeArr.includes(el))
}
